package io.github.wanggit.antrpc.console.zookeeper;

import io.github.wanggit.antrpc.console.web.vo.SubscribeConfigVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DefaultSubscribeConfigContainer implements ISubscribeConfigContainer {

    private final ConcurrentHashMap<String, SubscribeConfigVO> localStorges =
            new ConcurrentHashMap<>();

    @Override
    public void saveOrUpdate(SubscribeConfigVO subscribeConfigVO) {
        localStorges.put(subscribeConfigVO.getFullPath(), subscribeConfigVO);
    }

    @Override
    public void delete(SubscribeConfigVO subscribeConfigVO) {
        localStorges.remove(subscribeConfigVO.getFullPath());
    }

    @Override
    public List<String> findSubscribedHostInfos(String envName, String spaceName) {
        return localStorges.values().stream()
                .filter(
                        it ->
                                Objects.equals(envName, it.getEnvName())
                                        && Objects.equals(spaceName, it.getSpaceName()))
                .map(SubscribeConfigVO::getHostInfo)
                .sorted()
                .collect(Collectors.toList());
    }
}
